from django.shortcuts import render
from django.views.generic import View
from app1.models import *
from django.http import JsonResponse


# Create your views here.

class StuView(View):
    def get(self, request):
        # 1. 根据id获取数据 【queryset,queryset】
        stu = Student.objects.all()

        # 2. 调整数据格式
        aa = []
        for x in stu:
            context = {
                'name': x.name,
                'age': x.age,
                'score': x.score,
                'grade': x.grade_id,
                'grade_name': x.grade.name,
            }
            aa.append(context)
        # 3. 数据返回
        return JsonResponse(aa, safe=False)

    def post(self, request):
        # 1 获取前端穿过来的数据
        name = request.POST.get('name')
        age = request.POST.get('age')
        score = request.POST.get('score')
        grade_id = request.POST.get('grade_id')
        # 2. 数据效验
        try:
            Student.objects.get(name=name)
        except Student.DoesNotExist:
            # 3. 添加
            Student.objects.create(
                name=name, age=age,
                score=score, grade_id=grade_id
            )
            # s= Student(name=name,age=age,
            #     score=score,grade_id=grade_id)
            # s.save()
            context = {'msg': '添加成功', 'code': 200}
        else:
            context = {'msg': '重名', 'code': 200}
        # 数据返回
        return JsonResponse(context)
